<template>
  <view>
    <uni-popup
      ref="popupRef"
      background-color="#E5E7E7"
      borderRadius="12px 12px 12px 12px"
      type="dialog"
    >
      <view class="popup-content">
        <view class="popup-header">
          <view class="header-title">分享跑团</view>
          <image
            class="header-close"
            src="../static/icon-guanbi.png"
            @tap="hidePopup"
          ></image>
        </view>
        <view class="share-content">
          <!--    二维码      -->
          <view class="share-item" @tap="openQrcodeRef">
            <image class="icon" :src="shareIcon1"></image>
            <text class="label">跑团二维码</text>
          </view>
          <!--    分享朋友圈      -->
          <!--          <view class="share-item" @tap="shareTimeLine">-->
          <!--            <image class="icon" :src="shareIcon2"></image>-->
          <!--            <text class="label">朋友圈</text>-->
          <!--          </view>-->
          <!--    分享给好友      -->
          <view class="share-item">
            <button data-name="shareBtn" open-type="share" class="share">
              <image class="icon" :src="shareIcon3"></image>
              <text class="label">微信好友</text>
            </button>
          </view>
        </view>
      </view>
    </uni-popup>
    <uni-popup ref="qrcodeRef" class="qrcodeImg" type="center">
      <view class="qrcode-wrap">
        <view class="qrcode-popup-content">
          <view class="qr-header">
            <view class="avatar">
              <image
                class="icon"
                :src="
                  groupInfo && groupInfo.groupHeadImage ? groupInfo.groupHeadImage : ''
                "
              ></image>
            </view>
            <view class="group-name">
              <text class="name">{{
                groupInfo && groupInfo.groupName ? groupInfo.groupName : ""
              }}</text>
              <text class="count"
                >{{
                  groupInfo && groupInfo.memberNumber ? groupInfo.memberNumber : ""
                }}位成员</text
              >
            </view>
          </view>
          <image
            v-if="state.codeType === 'service'"
            class="group-qrcode"
            :src="state.companyCode"
          ></image>
          <image
            v-else
            class="group-qrcode"
            :src="groupInfo && groupInfo.groupCode ? groupInfo.groupCode : ''"
          ></image>
          <text class="label-text">{{ state.codeType === "service" ? "打开微信扫码，加入跑团微信群聊、兑奖咨询" : "打开微信扫码，加入我的跑团"}}</text>
        </view>
        <view class="saveQrcode" @tap="saveQrcode">保存</view>
      </view>
    </uni-popup>
    <canvas
      canvas-id="myCanvas"
      ref="myCanvasRef"
      style="position: absolute; top: -10000000px; width: 300px; height: 400px"
    ></canvas>
  </view>
</template>

<script setup name="PictureUpload">
import {
  onLaunch,
  onShow,
  onHide,
  onUnload,
  onShareAppMessage,
  onShareTimeline,
} from "@dcloudio/uni-app";
import {
  reactive,
  ref,
  toRefs,
  watch,
  onMounted,
  getCurrentInstance,
  nextTick,
} from "vue";
import * as API from "../../api/api";
import { storeToRefs } from "pinia";
import { useRunInfoStore } from "../../store/runInfo";
import { useGroupStore } from "../../store/group";
import UniPopup from "@/uni_modules/uni-popup/components/uni-popup/uni-popup.vue";
import shareIcon1 from "../static/erweima.png";
import shareIcon2 from "../static/pengyouquan.png";
import shareIcon3 from "../static/haoyouz.png";
import addressIcon from "../../static/address.png";
const useGroupData = useGroupStore();
const useRunInfoData = useRunInfoStore();
const { proportionShow, initStatus, timerNum, centerDistance, runType } = storeToRefs(
  useRunInfoData
);
const appInstance = getCurrentInstance().proxy;
const { groupInfo, groupType } = storeToRefs(useGroupData);
const popupRef = ref(null);
const qrcodeRef = ref(null);
const state = reactive({
  groupPicture: null,
  groupName: null,
  userInfo: null,
  codeType: null,
  companyCode: "https://model-capability.oss-cn-beijing.aliyuncs.com/pro/healthRun/qiyeerweima.png"
});
const myCanvasRef = ref();

const hidePopup = () => {
  popupRef.value.close("bottom");
};

const openPopup = () => {
  popupRef.value.open("bottom");
};
//  打开二维码
const openQrcodeRef = (type) => {
  console.log("type", type)
  state.codeType = type || null
  console.log("state.codeType", state.codeType)
  hidePopup();
  nextTick(() => {
    qrcodeRef.value.open();
  });
};
//  关闭二维码
const closeQrcodeRef = () => {
  state.codeType = null
  qrcodeRef.value.close();
};

// 绘制保存二维码
const drawCanvas = () => {
  const width = 286;
  const height = 360;
  const ctx = wx.createCanvasContext("myCanvas");

  // 绘制背景
  ctx.setFillStyle("#ffffff");
  ctx.fillRect(0, 0, width, height);

  // 绘制文本
  ctx.setFillStyle("#000000");
  ctx.setFontSize(20);
  const options = [
    {
      type: "block",
      radius: 8,
      isGradient: true,
      startColor: "#DDFFD8",
      endColor: "#FFFFFF",
      left: 0,
      top: 80,
      width: 286,
      height: 360,
    },
    // 二维码
    {
      type: "image",
      url: groupInfo.value?.groupCode,
      left: 41,
      top: 0,
      width: 206,
      height: 206,
    },
    // 头像
    {
      type: "image",
      url: groupInfo.value?.groupHeadImage,
      radius: "8px",
      left: 16,
      top: 16,
      width: 54,
      height: 54,
    },
    // 名称
    {
      type: "text",
      content: groupInfo.value?.groupName,
      // maxLine: 1,
      color: "#222222",
      fontSize: 16,
      left: 78,
      top: 22,
      width: 100,
      height: 22,
    },
    // 成员
    {
      type: "text",
      content: `${groupInfo.value.memberNumber}位成员`,
      color: "#E9F6E3",
      fontSize: 12,
      left: 78,
      bottom: 46,
    },
    // 地点
    {
      type: "text",
      content: "打开微信长按扫码，加入我的跑团",
      color: "#E9F6E3",
      fontSize: 14,
      left: "center",
      bottom: 17,
    },
  ];

  myCanvasRef.value.onDraw(
    options,
    (url) => {
      console.log(url);
    },
    () => {}
  );
};

// 保存二维码
const saveQrcode = () => {
  uni.downloadFile({
    url: state.codeType === "service" ? state.companyCode : groupInfo.value?.groupCode,
    success: (res) => {
      if (res.statusCode === 200) {
        uni.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: () => {
            uni.showToast({
              title: "保存成功",
              icon: "success",
            });
            closeQrcodeRef();
          },
          fail: (err) => {
            if (err.errMsg.includes("auth deny") || err.errMsg.includes("auth denied")) {
              uni.showModal({
                title: "提示",
                content: "请授权保存图片到相册",
                showCancel: false,
                success: () => {
                  uni.openSetting();
                },
              });
            } else {
              uni.showToast({
                title: "保存失败",
                icon: "none",
              });
            }
          },
        });
      }
      console.log(res);
    },
    fail: (res) => {
      console.log(res);
    },
  });
};

// 分享给朋友
onShareAppMessage(() => {
  const pages = getCurrentPages();
  // 获取当前页面实例
  const currentPage = pages[pages.length - 1];
  const options = currentPage.options;
  console.log(Object.keys(options), currentPage, 3333333);
  return {
    title: "2024廊坊首届全民健康走跑大会火热进行中，奔跑廊坊，体育场等你！",
    // path: `/runGroupPages/group/groupInfo?shareUserId=${state.userInfo?.customers?.customerId}&groupId=${groupInfo.value?.groupId}&type=share`
    path: `${currentPage.route}?shareUserId=${state.userInfo?.customers?.customerId}&groupId=${
      groupInfo.value?.groupId
    }&type=share&groupType=${groupType.value}`,
    // imageUrl: groupInfo.value?.groupHeadImage
  };
});
// 分享到朋友圈
onShareTimeline((res) => {
  return {
    title: "2024廊坊首届全民健康走跑大会火热进行中，奔跑廊坊，体育场等你！",
    query: `shareUserId=${state.userInfo?.customers?.customerId}&groupId=${groupInfo.value?.groupId}&type=share`,
    // imageUrl: groupInfo.value?.groupHeadImage
  };
});

onShow(() => {
  state.userInfo = uni.getStorageSync("userInfo")
    ? JSON.parse(uni.getStorageSync("userInfo"))
    : null;
});

defineExpose({
  openPopup,
  hidePopup,
  openQrcodeRef,
  closeQrcodeRef,
});
</script>

<style lang="scss">
.popup-content {
  width: 100vw;
  height: 660rpx;
  padding: 32rpx;
  box-sizing: border-box;
  .popup-header {
    display: flex;
    justify-content: space-between;
    .header-title {
      font-weight: 500;
      font-size: 36rpx;
      color: #1c1c1e;
    }
    .header-close {
      width: 56rpx;
      height: 56rpx;
    }
  }
  .share-content {
    height: 540rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    .share-item {
      width: 156rpx;
      border-radius: 16rpx;
      margin-right: 48rpx;
      .share {
        width: 156rpx;
        height: 212rpx;
        border: none;
        padding: 0;
        margin: 0;
        background: transparent;
      }
      .share:after {
        content: none;
      }
      .share::after {
        border: none;
      }
      .icon {
        display: block;
        width: 156rpx;
        height: 156rpx;
        border-radius: 16rpx;
        background: #ffffff;
      }
      .label {
        display: block;
        width: 156rpx;
        text-align: center;
        height: 40rpx;
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        font-size: 28rpx;
        color: rgba(28, 28, 30, 0.8);
        line-height: 40rpx;
        text-align: center;
        font-style: normal;
        margin-top: 16rpx;
      }
    }
    .share-item:last-child {
      margin-right: 0;
    }
  }
}
.qrcodeImg {
  .qrcode-wrap {
    position: fixed;
    left: 50%;
    top: 50%;
    margin-left: -282rpx;
    margin-top: -430rpx;
    width: 572rpx;
    height: 860rpx;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    .qrcode-popup-content {
      display: block;
      width: 572rpx;
      height: 720rpx;
      background: linear-gradient(180deg, #ddffd8 0%, #ffffff 100%);
      border-radius: 24rpx;
      padding: 32rpx;
      box-sizing: border-box;
      overflow: hidden;
      .qr-header {
        height: 108rpx;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        .avatar {
          width: 108rpx;
          height: 108rpx;
          background: #ebebeb;
          border-radius: 16rpx;
          overflow: hidden;
          margin-right: 16rpx;
          .icon {
            width: 100%;
            height: 100%;
          }
        }
        .group-name {
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: flex-start;
          height: 108rpx;
          overflow: hidden;
          .name {
            width: 320rpx;
            display: block;
            height: 44rpx;
            font-family: PingFangSC, PingFang SC;
            font-weight: 500;
            font-size: 32rpx;
            color: #222222;
            line-height: 44rpx;
            text-align: left;
            font-style: normal;
            white-space: nowrap;
            text-overflow: ellipsis;
            overflow: hidden;
          }
          .count {
            display: block;
            height: 40rpx;
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            font-size: 28rpx;
            color: rgba(34, 34, 34, 0.7);
            line-height: 40rpx;
            text-align: left;
            font-style: normal;
            margin-top: 4rpx;
          }
        }
      }
      .group-qrcode {
        display: block;
        width: 413rpx;
        height: 413rpx;
        margin: 66rpx auto 28rpx;
      }
      .label-text {
        display: block;
        height: 40rpx;
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        font-size: 24rpx;
        color: rgba(34, 34, 34, 0.7);
        line-height: 40rpx;
        text-align: center;
        font-style: normal;
      }
    }
    .saveQrcode {
      width: 572rpx;
      height: 100rpx;
      line-height: 100rpx;
      margin-top: 40rpx;
      background: #08cb8f;
      border-radius: 24rpx;
      text-align: center;
      overflow: hidden;
      color: #fff;
    }
  }
}
</style>
